package security;

import models.User;

import com.feth.play.module.pa.PlayAuthenticate;
import com.feth.play.module.pa.user.AuthUserIdentity;

import controllers.Application;

import play.mvc.Http.Context;
import play.mvc.Result;

import be.objectify.deadbolt.core.models.Subject;
import be.objectify.deadbolt.java.AbstractDeadboltHandler;
import be.objectify.deadbolt.java.DynamicResourceHandler;

public class ConsoleDeadboltHandler extends AbstractDeadboltHandler {
	
	@Override
	public Result beforeAuthCheck(final Context context) {
		if (PlayAuthenticate.isLoggedIn(context.session())) {
			return null;
		} else {
			final String originalUrl = PlayAuthenticate.storeOriginalUrl(context);
			context.flash().put(Application.FLASH_ERROR_KEY, "You need to log in to access '" + originalUrl + "'.");
			return redirect(PlayAuthenticate.getResolver().login());
		}
	}
	
	@Override
	public Subject getSubject(final Context context) {
		final AuthUserIdentity identity = PlayAuthenticate.getUser(context);
		return User.findByAuthUserIdentity(identity);
	}
	
	@Override
	public DynamicResourceHandler getDynamicResourceHandler(final Context context) {
		return null;
	}
	
	@Override
	public Result onAuthFailure(final Context context, final String content) {
		final String originalUrl = PlayAuthenticate.storeOriginalUrl(context);
		context.flash().put(Application.FLASH_ERROR_KEY, "You do not have permission to access '" + originalUrl + "'.");
		return redirect(PlayAuthenticate.getResolver().login());
	}
	
}
